package j20251031;

public class Solution1 {
    int m,n;
    boolean[][] visit;
    public boolean exist(char[][] board, String word) {
        m=board.length;
        n=board[0].length;
        visit=new boolean[m][n];
        char target=word.charAt(0);
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(visit[i][j]==false&&board[i][j]==target){
                    visit[i][j]=true;
                    if(dfs(board,i,j,word,1)) return true;
                    visit[i][j]=false;
                }
            }
        }
        return false;
    }
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    public boolean dfs(char[][] board,int i,int j,String word,int pos){
        if(pos==word.length()) return true;
        char target=word.charAt(pos);
        for(int k=0;k<4;k++){
            int x=i+dx[k];
            int y=j+dy[k];
            if(x>=0&&x<m&&y>=0&&y<n&&visit[x][y]==false&&board[x][y]==target){
                visit[x][y]=true;
                if(dfs(board,x,y,word,pos+1)) return true;
                visit[x][y]=false;
            }
        }
        return false;
    }
}
